package com.zhuangjie.event.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhuangjie.event.service.AbstractModuleEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class AutoRegister {
    @Autowired
    protected RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private List<AbstractModuleEventService> abstractModuleEventServiceList;

    /**
     * 为List<AbstractModuleEventService>进行调用AbstractModuleEventService::register传入map收集注册
     * @return
     */
    @Bean
    protected RedisMessageListenerContainer register() {
        RedisMessageListenerContainer container =  new RedisMessageListenerContainer();

        // 监听所有库的key过期事件
        container.setConnectionFactory(redisConnectionFactory);

        // 可以添加多个 messageListener，配置不同的通道
        Map<MessageListener, Collection<? extends Topic>> mp = new HashMap<>();
        abstractModuleEventServiceList.forEach(abstractModuleEventService->abstractModuleEventService.register(mp));
        container.setMessageListeners(mp);
        /**
         * 设置序列化对象
         * 特别注意：1. 发布的时候需要设置序列化；订阅方也需要设置序列化
         *         2. 设置序列化对象必须放在[加入消息监听器]这一步后面，否则会导致接收器接收不到消息
         */
        Jackson2JsonRedisSerializer seria = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        seria.setObjectMapper(objectMapper);
        container.setTopicSerializer(seria);

        return container;
    }
}
